package com.example.adabank3.shiro;


import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * shiro配置类
 * @author Administrator
 */
@Configuration
public class ShiroConfig {
    //3、ShiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Autowired DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);
        //添加shiro的内置过滤器
        /**
         * anon：无需认证即可访问
         * authc：必须认证才能访问
         * user：必须拥有记住我功能才能用
         * perms：拥有对某个资源的权限才能访问
         * role：拥有某个角色权限才能访问
         */
        Map<String, String> filterMap = new LinkedHashMap<>();
        //必须认证才能访问
//        filterMap.put("/user/adduser","authc");
//        filterMap.put("/user/updateuser","authc");
        filterMap.put("/api/customers","perms[administrator]");
        filterMap.put("/api/customers","perms[manage]");
        filterMap.put("/user/**","perms[user]");
        bean.setFilterChainDefinitionMap(filterMap);
        //设置未登录时跳到登录页面
        bean.setLoginUrl("/login");
        //未经授权无法访问
        bean.setUnauthorizedUrl("/unauth");
        return bean;
    }
    //2、DefaultWebSecurityManager
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Autowired UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联userRealm
        securityManager.setRealm(userRealm);
        return securityManager;
    }
    //1、创建UserRealm 需自定义类
    @Bean
    public UserRealm getUserRealm(){
        return new UserRealm();
    }
}

